package gxprod.androidai.support;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class MetricsLogger {

	private static final String FAILED_VOICE = "failedVoiceIndex";
	private static final String FAILED_TEXT = "failedTextIndex";
	private static final String FAILED_VOICE_PUT = "failedVoice_";
	private static final String FAILED_TEXT_PUT = "failedText_";

	private static SharedPreferences prefs;
	private static Editor edit;

	private static int failedVoiceIndex;
	private static int failedTextIndex;

	public static boolean IsEnabled;

	public static void Prepare(Context context) {
		prefs = context.getSharedPreferences("androidai.metrics", Context.MODE_PRIVATE);
		edit = prefs.edit();
		failedVoiceIndex = prefs.getInt("failedVoiceIndex", 0);
		failedTextIndex = prefs.getInt(FAILED_TEXT, 0);
	}

	public static void LogTextCommandFailure(String match) {
		if(IsEnabled) {
			edit.putString(FAILED_TEXT_PUT + failedTextIndex, match);
			failedTextIndex++;
		}
	}

	public static void LogVoiceCommandFailure(String[] matches) {
		if(IsEnabled) {
			StringBuilder sb = new StringBuilder();
			sb.append(matches[0]);
			for(int i = 1; i < matches.length; i++) {
				sb.append(":=:");
				sb.append(matches[i]);
			}
			edit.putString(FAILED_VOICE_PUT + failedVoiceIndex, sb.toString());
			failedVoiceIndex++;
		}
	}

	public static void save() {
		edit.putInt(FAILED_VOICE, failedVoiceIndex);
		edit.putInt(FAILED_TEXT, failedTextIndex);
		edit.apply();
	}

	public static boolean compleatSave() {
		return edit.commit();
	}

	public static boolean Submit() {
		boolean sucess = false;
		edit.commit();
		try {

			// TODO: submit anonymously to GXProductionsInc@Gmail.com

			sucess = true;
		} catch(Exception ex) {
			ex.printStackTrace();
		}

		if(sucess) 
			edit.clear();
		return sucess;
	}
}
